package com.family.system.controller;

import com.family.common.result.Result;
import com.family.common.result.ResultCodeEnum;
import com.family.model.system.SysUser;
import com.family.model.vo.LoginVo;
import com.family.system.exception.GuiguException;
import com.family.system.service.SysUserService;
import com.family.common.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName IndexController
 * @Date 2023-05-08 11:00
 * @AUTHOR family
 **/
@Api(tags = "初始化控制")
@RestControllerAdvice
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<Object> login(@RequestBody LoginVo loginVo) {
        //查询数据库用户，判断用户是否存在
        SysUser sysUser = sysUserService.getByUsername(loginVo.getUsername());
        if (null == sysUser) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        //判断密码是否正确
        if (!MD5.encrypt(loginVo.getPassword()).equals(sysUser.getPassword())) {
            throw new GuiguException(ResultCodeEnum.PASSWORD_ERROR);
        }
        //判断用户状态是否正常使用
        if (sysUser.getStatus() == 0) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }
        Map<String, String> map = new HashMap<>();
        //生成UUID
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.boundValueOps(token).set(sysUser, 2, TimeUnit.HOURS);
        //返回用户的UUID
        map.put("token", token);
        return Result.ok(map);
    }

    /**
     * 获取用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public Result<Map<String, Object>> info(HttpServletRequest request) {
        //获取请求头中的token
        String token = request.getHeader("token");
        //根据token获取Redis中的用户信息
        SysUser sysUser = (SysUser) redisTemplate.boundValueOps(token).get();
        //调用SysUserService中根据用户id获取用户信息的方法
        Map<String, Object> map = sysUserService.getUserInfoByUserId(sysUser.getId());
        return Result.ok(map);
    }

    /**
     * 退出
     */
    @ApiOperation("用户退出")
    @PostMapping("/logout")
    public Result<Map<String, Object>> logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        redisTemplate.delete(token);
        return Result.ok();
    }
}
